# 批量获取目录下的所有PDF文件并合并成一个PDF文件
import os
from PyPDF2 import PdfMerger, PdfReader

def get_output_filename(input_directory):
    parts = input_directory.split(os.sep)[-1]
    return f'{parts}.pdf'

def merge_pdfs(input_directory):
    if not input_directory:
        return { 'error': '请输入有效的目录路径'}
    try:
        output_pdf_path = os.path.join(input_directory, get_output_filename(input_directory))
        merger = PdfMerger()

        for root, dirs, files in os.walk(input_directory):
            for file in files:
                if file.endswith('.pdf'):
                    file_path = os.path.join(root, file)
                    with open(file_path, 'rb') as f:
                        pdf_reader = PdfReader(f)
                        merger.append(pdf_reader)

        with open(output_pdf_path, 'wb') as f:
            merger.write(f)
        return {'success': output_pdf_path}
    except Exception as e:
        print(f"发生错误：{e}")
        return {'error': str(e)}

if __name__ == "__main__":
    input_dir = r''
    merge_pdfs(input_dir)
